<style>
    .file-container {
        width: 100%;
        height: 500px;
        border-width: 0px;
        border-style: solid;
        background-color: #fff;
        border-radius: 2px;
        border-color: #e6e6e6;
        overflow: auto;
    }

    .file-container .file {
        height: 170px;
        width: 170px;
        margin-left: 10px;
        margin-top: 10px;
        margin-bottom: 0px;
        margin-right: 0px;
        border-width: 0px;
        border-style: solid;
        background-color: #fff;
        border-radius: 2px;
        border-color: #e6e6e6;
    }

    .operation-btn {
        height: 20px;
        width: 178px;
        text-align: center;
    }

    .file-name{
        text-align: center;
    }

    #notice-form .text {
        /*border: 1px solid #ccc;*/
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
    }

    .layui-form-tool{
        z-index: 19911128;
    }

    .layui-anim-upbit{
        z-index: 999999999999999!important;
    }
</style>
<div style="padding: 20px 0px; overflow-x: hidden;" id="notice-form">

    <form class="layui-form" onsubmit="return false"  id="form" lay-filter="form">

        <input type="hidden" name="id" value="${RequestParameters.id!}"/>

        <div class="layui-row layui-col-space15 layui-form-item">

            <div class="layui-col-xs1">
            </div>

            <div class="layui-col-xs9">
                <label class="layui-form-label"><i class="require">* &nbsp;</i>接收者:</label>
                <div class="layui-input-block">
                    <div style="width:15%; display: inline-block;">
                        <select name="type" id="type" lay-dict="NOTICE_RECEIVER_TYPE" required="" lay-verify="required" lay-filter="type">

                        </select>
                    </div>
                    <input type="text" id="recivers" name="recivers" autocomplete="off" class="layui-input" readonly="readonly" style="display: inline-block;width:84%">
                </div>
            </div>

            <div class="layui-col-xs2">
            </div>

        </div>

        <div class="layui-row layui-col-space15 layui-form-item">

            <div class="layui-col-xs1">
            </div>

            <div class="layui-col-xs9">
                <label class="layui-form-label"><i class="require">* &nbsp;</i>标题:</label>
                <div class="layui-input-block">
                    <#--<div style="width:15%; display: inline-block;">
                        <select name="topState" id="topState" lay-dict="NOTICE_TOP_STATE" required="" lay-verify="required">

                        </select>
                    </div>
                    <input type="text" id="title" name="title" required="" lay-verify="required" autocomplete="off" class="layui-input" style="display: inline-block;width:84%">-->
                    <input type="text" id="title" name="title" required="" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-col-xs2">
            </div>

        </div>

        <div class="layui-row layui-col-space15 layui-form-item">

            <div class="layui-col-xs1">
            </div>

            <div class="layui-col-xs9">
                <label class="layui-form-label"><i class="require">* &nbsp;</i>正文:</label>
                <div class="layui-input-block">
                    <textarea name="content" style="display: none;"></textarea>
                    <div id="content" class="text"></div>
                </div>
            </div>

            <div class="layui-col-xs2">
            </div>

        </div>

        <div class="layui-row layui-col-space15 layui-form-item layui-form-text">

            <div class="layui-col-xs1">
            </div>

            <div class="layui-col-xs9">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="select-file-btn">
                        <i class="layui-icon">&#xe681;</i>选择附件
                    </button>
                </div>
            </div>

            <div class="layui-col-xs2">
            </div>

        </div>

        <div class="layui-row layui-col-space15 layui-form-item layui-form-text" id="file_list_panel"
             style="display: none;">

            <div class="layui-col-xs1">
            </div>

            <div class="layui-col-xs9">
                <div class="layui-input-block">
                    <div class="file-container">

                    </div>
                </div>
            </div>

            <div class="layui-col-xs1">
            </div>

        </div>

        <div class="layui-row">
            <div class="layui-layer-btn layui-layer-btn-c layui-form-tool">
                <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit_btn" id="submit_btn" style="display: none;">保存</button>
                <button type="submit" class="layui-btn layui-btn-warm" lay-submit="" lay-filter="release_btn" id="release_btn" style="display: none;">发布</button>
                <button type="button" class="layui-btn layui-btn-primary" id="view_btn">预览</button>
                <button type="button" class="layui-btn layui-btn-primary" lay-filter="cancle_btn">取消</button>
            </div>
        </div>

    </form>

</div>

<script>
    layui.use(['form', 'http', 'jquery', 'FdpUtil', 'upload', 'util'], function(){

        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form,
            http = layui.http,
            upload = layui.upload,
            util = layui.util;

        var MODULE = "SYS-NOTICE";

        var id = $("#form").find("input[name='id']").val();
        var recivers = [];

        var files = [];

        var appendFile = function(fileObj){

            if (FileType.isImg(fileObj.originalName)) {

                $(".file-container").append("<div id='file-" + fileObj.id + "' style='display: inline-block;' name='img-div' title='" + fileObj.originalName + "'><img class='file' src='" + Appendix.getDownLoadUrl(fileObj.id) + "'/><div class='file-name' title='" + fileObj.originalName + "'>" + fileObj.originalName + "</div><div class='operation-btn'><a name='file-del-btn' file-id='" + fileObj.id + "' class='text-blue' href='javascript:;'>删除</a> | <a name='file-download-btn' file-id='" + fileObj.id + "' class='text-blue' href='javascript:;'>下载</a></div></div>");

            } else {

                $(".file-container").append("<div id='file-" + fileObj.id + "' style='display: inline-block;' name='pdf-div' title='" + fileObj.originalName + "'><img file-id='" + fileObj.id + "' isPdf='" + (fileObj.originalName.indexOf('.pdf') >= 0) + "' class='file' src='" + (fileObj.originalName.indexOf('.pdf') > 0 ? '${context.contextPath}/static/img/pdf-default.png' : '${context.contextPath}/static/img/file-default.png') + "'/><div class='file-name' title='" + fileObj.originalName + "'>" + fileObj.originalName + "</div><div class='operation-btn'><a name='file-del-btn' file-id='" + fileObj.id + "' class='text-blue' href='javascript:;'>删除</a> | <a name='file-download-btn' file-id='" +fileObj.id + "' class='text-blue' href='javascript:;'>下载</a></div></div>");
            }

            files.push(fileObj.id);

            $("a[name='file-del-btn']").unbind().click(function () {

                var id = $(this).attr("file-id");

                files.splice($.inArray(id, files), 1);

                $("#file-" + id).remove();

                if (files.length > 0) {
                    $("#file_list_panel").show();
                } else {
                    $("#file_list_panel").hide();
                }
            });

            $("a[name='file-download-btn']").unbind().click(function () {

                var id = $(this).attr("file-id");

                top.window.open(Appendix.getDownLoadUrl(id));
            });

            Appendix.imgPreview("div[name='img-div']");

            $("div[name='pdf-div'] img").unbind().click(function () {

                var id = $(this).attr("file-id");
                var isPdf = $(this).attr("isPdf");

                if (isPdf == "true") {

                    Appendix.pdfPreview(id);

                } else {
                    layer.msg("不支持在线浏览!");
                }
            })

            if (files.length > 0) {
                $("#file_list_panel").show();
            } else {
                $("#file_list_panel").hide();
            }
        }

        form.render();//渲染表单

        form.on('select(type)', function(data){
            recivers = [];
            $("#form").find("input[name='recivers']").val("");
        })

        $("#form").find("input[name='recivers']").click(function () {

            var type = $("#form").find("select[name='type']").val();

            console.info('type:' + type);

            var checked = [];
            for (var i = 0; i < recivers.length; i++){
                checked.push(recivers[i].id);
            }

            if(type == GLOBAL.constant.Dict.NOTICE_RECEIVER_TYPE.DEPT.value){

                Org.selectDept({
                    callBack: {
                        module: MODULE,
                        cmdName: "setRecivers",
                    },
                    checked: checked,
                    singleFlag: false
                })

            }else if(type == GLOBAL.constant.Dict.NOTICE_RECEIVER_TYPE.EMPLOYEE.value){

                Org.selectUser({
                    callBack: {
                        module: MODULE,
                        cmdName: "setRecivers",
                    },
                    checked: checked,
                    singleFlag: false
                })

            }

            //设置部门
            FdpCommand.register({
                module: MODULE,
                cmdName: "setRecivers",
                callBack: function (options) {

                    fillReciverNames(options);
                }
            })
        })

        var fillReciverNames = function (options) {

            recivers = options;

            if(recivers.length > 0){

                var reciverNames = [];
                for (var i = 0; i < recivers.length; i++){
                    reciverNames.push(recivers[i].name);
                }

                $("#form").find("input[name='recivers']").val(reciverNames.join("、"));

            }else{
                $("#form").find("input[name='recivers']").val("");
            }
        }

        if(id.length > 0){
            http.get({
                url: GLOBAL.path.adminApi + '/sys/notice/get/' + id,
                async: false,
                backFun: function(result){

                    form.val("form", result);

                    form.render("select");//渲染表单

                    var fileObjs = Appendix.find(result.id, Appendix.Type.DefaultType);

                    if(fileObjs){
                        for(var i = 0; i < fileObjs.length; i++){
                            appendFile(fileObjs[i]);
                        }
                    }

                    fillReciverNames(JSON.parse(result.recivers));

                    if(result.state == GLOBAL.constant.Dict.NOTICE_STATE.BOOKED.value){

                        $("#form").find("#submit_btn").show();
                        $("#form").find("#release_btn").show();

                    }else if(result.state == GLOBAL.constant.Dict.NOTICE_STATE.RELEASE.value){

                        $("#form").find("#release_btn").hide();
                    }
                }});
        }else{
            $("#form").find("#submit_btn").show();
        }

        var openMaterial = function(type, title){

            Win.open({
                url: GLOBAL.path.basePath + "/view/base/material/select?busType=${RequestParameters.type!}&materialType=" + type + "&module=" + MODULE,
                title: title,
                type: 1,
                width: '800px'
            })
        }

        Editor.init({
            container: [$("#form").find("#content")[0]],
            syncTextArea: $("#form").find("textarea[name='content']"),
            contenteditable: true,
            content: $("#form").find("textarea[name='content']").val(),
            showMenus: true,
            height: 600,
            showFullScreen: false,
            imgMenuClickEvent: function($this){
                openMaterial(GLOBAL.constant.Dict.MATERIAL_TYPE.IMG.value, "从素材库选择或上传图片");

                FdpCommand.register({
                    module: MODULE,
                    cmdName: "uploadImg",
                    callBack: function (urls) {
                        console.info("uploadImg:" + urls)

                        imgInsert($this.editor, urls);
                    }
                })
            },
            videoMenuClickEvent: function($this){
                openMaterial(GLOBAL.constant.Dict.MATERIAL_TYPE.VIDEO.value, "从素材库选择或上传视频");

                FdpCommand.register({
                    module: MODULE,
                    cmdName: "uploadVideo",
                    callBack: function (urls) {
                        console.info("uploadVideo:" + urls)

                        videoInsert($this.editor, urls);
                    }
                })
            }
        });

        //监听提交
        form.on('submit(submit_btn)', function(data) {

            submit({
                params: data.field
            })

        });

        var submit = function (options) {

            var params = options.params;

            params.recivers = JSON.stringify(recivers);
            params.files = files;

            http.post({'url': GLOBAL.path.adminApi + '/sys/notice/' + (id ? 'modify': 'add'),
                'data': params,
                'backFun': function(result){

                    if(options.backFun){
                        options.backFun();
                        return;
                    }

                    top.layui.layer.msg("操作成功！");

                    if(!id){
                        id = result.id;
                    }

                    FdpCommand.execute({
                        module: MODULE,
                        cmdName: "refreshTable",
                        options: result
                    })

                }})

            return false;
        }

        var uploadFile = upload.render({
            elem: '#select-file-btn'
            , url: Appendix.getUploadUrl()
            , accept: 'file'
            , before: function (obj) {
            }
            , done: function (res) {

                if (res.code == GLOBAL.returnCode.OK) {

                    appendFile(res.data);

                } else {

                    return layer.msg('上传失败');
                }
            }
            , error: function () {
                layer.msg("上传失败");
            }
        });

        var imgInsert = function(editor, urls){

            if(!urls || urls.length <= 0){
                return;
            }

            const config = editor.config

            for(var i = 0; i < urls.length; i++){

                var url = urls[i];

                // 先插入图片，无论是否能成功
                editor.cmd.do('insertHTML', '<img src="' + url + '" style="max-width:100%;"/>')
                // 执行回调函数
                config.linkImgCallback(url)

                // 加载图片
                let img = document.createElement('img')
                img.onload = () => {
                    img = null
                }
                img.onabort = () => (img = null)
                img.src = url
            }
        }

        var videoInsert = function(editor, urls){

            if(!urls || urls.length <= 0){
                return;
            }

            for(var i = 0; i < urls.length; i++) {

                var url = urls[i];

                var video = "<p><video style='width: 100%;background-color: #000000;display: block;' controls='controls' autoplay='autoplay' oncanplay='this.play()' preload='auto' x-webkit-airplay='true' x5-playsinline='true' webkit-playsinline='true' playsinline='true' webkit-playsinline='true' playsinline='true'><source src='" + url + "'  type='video/mp4'/></video></p>";
                var iframe = "<iframe srcdoc=\"" + video + "\" style='border: 0px;width: 100%;'></iframe>";

                editor.cmd.do('insertHTML', video + '<p><br></p>')

                // video添加后的回调
                editor.config.onlineVideoCallback(video)
            }
        }

        $("#view_btn").click(function(){

            if(!id){
                layer.msg('请先保存!');

                return;
            }

            Win.open({
                url: GLOBAL.path.basePath + "/view/sys/notice/preView?id=" + id,
                width: '50%',
                height: '60%',
                type: 1,
                offset: 't',
                anim: 0,
                skin: '-1',
                isOutAnim: false
            })
        })

        $("#release_btn").click(function(){

            if(!id){
                layer.msg('请先保存!');

                return;
            }

            submit({
                params: form.val("form"),
                backFun: function () {

                    layer.confirm('发布确认，请确认!', function (index) {

                        http.post({
                            url: GLOBAL.path.adminApi + '/sys/notice/release?id=' + id,
                            async: false,
                            backFun: function (result) {

                                layer.msg("已发布");

                                FdpCommand.execute({
                                    module: MODULE,
                                    cmdName: "refreshTable",
                                    options: result
                                })

                                setTimeout(function () {

                                    $("button[lay-filter='cancle_btn']").click();
                                }, 500);
                            }
                        });
                    });
                }
            })
        })
    });
</script>


